package com.webapp.model;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Time;
import java.util.ArrayList;

public class MessageModel {
	
	private Statement stmt = DatabaseConnector.connect();
	
	//	public Message(int mess, String dater, String sub, String cont, int send, int rec)
	public Message getMessage(int messId){
		try{
			ResultSet rs = stmt.executeQuery("SELECT * FROM messages WHERE Message_Id = '" +messId+ "'");
			if(rs.next()){
				
				Time t = rs.getTime(2);
				Date d = rs.getDate(2);
				String messDate = d.toString().concat(" "+t.toString());
				
				Message m = new Message(rs.getInt(1), messDate, rs.getString(3), rs.getString(4), rs.getInt(5), rs.getInt(6));
				
				return m;
			}
			else
				return null;
			
		}catch(Exception ex){return null;}
	}
	
	public ArrayList<Message> getSentMessageByUser(int userId){
		try{
			ResultSet rs = stmt.executeQuery("SELECT * FROM messages WHERE Sender = '" +userId+ "'");
			ArrayList<Message> list = new ArrayList<Message>();
			
			while(rs.next()){
				Time t = rs.getTime(2);
				Date d = rs.getDate(2);
				String messDate = d.toString().concat(" "+t.toString());
				
				Message m = new Message(rs.getInt(1), messDate, rs.getString(3), rs.getString(4), rs.getInt(5), rs.getInt(6));
				
				list.add(m);
			}
			return list;
			
		}catch(Exception ex){return null;}
	}
	
	public ArrayList<Message> getRecievedMessageByUser(int userId){
		try{
			ResultSet rs = stmt.executeQuery("SELECT * FROM messages WHERE Receiver = '" +userId+ "'");
			ArrayList<Message> list = new ArrayList<Message>();
			
			while(rs.next()){
				Time t = rs.getTime(2);
				Date d = rs.getDate(2);
				String messDate = d.toString().concat(" "+t.toString());
				
				Message m = new Message(rs.getInt(1), messDate, rs.getString(3), rs.getString(4), rs.getInt(5), rs.getInt(6));
				
				list.add(m);
			}
			return list;
			
		}catch(Exception ex){return null;}
	}
	
	public boolean createMessage(String subject, String content, int senderId, int recieverId){
		Message m = new Message(subject, content, senderId, recieverId);
		try{
			ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE User_Id = '" +recieverId+ "'");
			if(rs.next()){
				stmt.executeUpdate("INSERT INTO messages (Message_Id, Date, Subject, Content, Sender, Receiver) VALUES ('"+
						m.getMessageId()+ "', '" +m.getDate()+ "', '" +m.getSubject()+ "', '" +m.getContent()+ "', '" +m.getSender()+ 
						"', '" +m.getReciever()+ "')");
				return true;
			}
			else
				return false;
		}catch(Exception ex){return false;}
		
	}
	
	public boolean deleteMessage(int messageId){
		try{
			stmt.executeUpdate("DELETE FROM messages WHERE Message_Id = '" +messageId+ "'");
			return true;
		}catch(Exception ex){return false;}
	}
	
	
	
}
